package com.whj.account.web.constrollers;

import com.whj.account.service.AccountService;
import com.whj.account.service.AccountServiceException;
import com.whj.account.service.SignupRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@Controller
public class Login {

    @Autowired
    private AccountService accountService;

    @GetMapping("/login")
    public String getLoginForm(){
        return "login";
    }

    @GetMapping("/signup")
    public String getSignupForm(Model model) {
        try {
            String key = accountService.generateCaptchaKey();
            model.addAttribute("captchaKey", key);

            return "signup";
        } catch (AccountServiceException exp) {
            return "redirect:error";
        }
    }

    @PostMapping("/signup")
    public String postSignupForm(SignupRequest signupRequest, Model model) throws AccountServiceException{

        accountService.signUp(signupRequest);
        model.addAttribute("name", signupRequest.getName());
        return "home";
    }

    @GetMapping("/captcha/{key}")
    public void getCaptchaImage(@PathVariable("key") String key, HttpServletResponse response){
        try
        {
            response.setContentType("image/jpeg");
            byte[] image = accountService.generateCaptchaImage(key);
            response.getOutputStream().write(image);
        } catch (Exception exp) {

        }
    }
}
